package com.mysoft.gfyx.marketdevelop.service.impl;

import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.gfyx.common.dto.ListResult;
import com.mysoft.gfyx.common.dto.PagerDto;
import com.mysoft.gfyx.common.time.TimeService;
import com.mysoft.gfyx.common.util.MyStringUtil;
import com.mysoft.gfyx.marketdevelop.dao.entity.OpTelViewHistory;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.mip.dto.BaseTjFilterDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.BaseTjListResponseDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.GetDeveloperFilterDataRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.GetDeveloperSortDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.GetContactListRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.SqlApiResponseDto;
import com.mysoft.gfyx.marketdevelop.remoteService.RemoteClueService;
import com.mysoft.gfyx.marketdevelop.service.DeveloperContactService;
import com.mysoft.gfyx.marketdevelop.service.DeveloperService;
import com.mysoft.gfyx.marketdevelop.service.ProvinceRadarService;
import com.mysoft.gfyx.marketdevelop.service.dto.DeveloperContactDto;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeveloperContactServiceImp implements DeveloperContactService {

    @Autowired
    private DeveloperService developerService;

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Autowired
    private TimeService timeService;

    @Autowired
    private RemoteClueService remoteClueService;

    @Autowired
    private ProvinceRadarService provinceRadarService;

    public ListResult<DeveloperContactDto> getDeveloperContact(String id, PagerDto pagerDto) {
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_CONTACT_WITH_INVESTMENT);
        dto.setPage(pagerDto.getPage());
        dto.setPage_size(pagerDto.getPage_size());

        dto.addFilterDtos("organizing_code", BaseTjFilterDto.OPERATE_EQUAL, id, DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_NONE);

        // 排序
        ArrayList<GetDeveloperSortDto> sorts = new ArrayList<>();
        GetDeveloperSortDto sort = new GetDeveloperSortDto();
        sort.setSort_type(GetDeveloperSortDto.SORT_DESC);
        sort.setAttribute_name("created_at");
        sort.setTable_name(DeveloperService.TABLE_CONTACT_WITH_INVESTMENT);
        sorts.add(sort);
        dto.setSorts(sorts);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        ListResult<DeveloperContactDto> listDataResult = new ListResult<>();
        List<DeveloperContactDto> developerContactDtos = new LinkedList<>();
        if (res.getData() == null || res.getData().getList() == null) {
            listDataResult.setData(developerContactDtos);
            listDataResult.setTotal(0);
            return listDataResult;
        }

        listDataResult.setTotal(res.getData().getTotal());

        // 获取是否添加过线索
        List<String> purchasesId = res.getData().getList().stream().map(p -> p.getItem().get("purchase_demand_id").toString()).collect(Collectors.toList());
        Set<String> haveAdded = remoteClueService.isAdded(purchasesId);

        res.getData().getList().forEach(d -> {
            DeveloperContactDto developerContactDto = new DeveloperContactDto();
            developerContactDto.setId(d.getItem().get("id").toString());
            developerContactDto.setName(MyStringUtil.ReplaceSpecifiedStr(0, 1, d.getItem().get("ower").toString(), "*", 2));
            developerContactDto.setMobile(MyStringUtil.ReplaceSpecifiedStr(0, 3, d.getItem().get("ower_mobile").toString(), "*", 8));
            developerContactDto.setCreatedPeriod(timeService.getLatestPeriod(d.getItem().get("created_at")) + "更新");
            if (d.getItem().get("created_at") != null)
                developerContactDto.setUpdatedTime(d.getItem().get("created_at").toString());
            developerContactDto.setSource(d.getItem().get("purchase_demand_id").toString());
            developerContactDto.setSourceTitle(d.getItem().get("title").toString());
            developerContactDto.setCompany(d.getItem().get("sub_developer_name").toString());
            developerContactDto.setOrganizingCode(d.getItem().get("sub_organizing_code").toString());
            // 是否添加过
            int hasAdded = haveAdded.contains(d.getItem().get("purchase_demand_id").toString()) ? 1 : 0;
            developerContactDto.setIsInStock(hasAdded);

            developerContactDtos.add(developerContactDto);
        });

        listDataResult.setData(developerContactDtos);
        return listDataResult;
    }

    public List<Map<String, Object>> getPurchaseContacts(Set<String> ids) {
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_CONTACT_WITH_INVESTMENT);
        dto.setPage(1);
        dto.setPage_size(100);

        dto.addFilterDtos("purchase_demand_id", BaseTjFilterDto.OPERATE_CONTAIN, StringUtil.join(ids, ","), DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_NONE);
        //dto.addFilterDtos("data_source_code", BaseTjFilterDto.OPERATE_CONTAIN, "website_bid,trading_center", DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_AND);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        List<Map<String, Object>> listMap = new ArrayList<>();
        if (res.getData() == null || res.getData().getList() == null) {
            return listMap;
        }

        res.getData().getList().forEach(m -> {
            Map<String, Object> contact = new HashMap<>();
            contact.put("id", m.getItem().get("id").toString());
            contact.put("name", m.getItem().get("ower").toString());
            contact.put("mobile", m.getItem().get("ower_mobile").toString());
            contact.put("developer_name", m.getItem().get("developer_name").toString());
            contact.put("purchase_demand_id", m.getItem().get("purchase_demand_id").toString());
            contact.put("uid", m.getItem().get("uid").toString());
            contact.put("created_at", m.getItem().get("created_at").toString());
            listMap.add(contact);
        });
        return listMap;
    }

    public List<Map<String, Object>> getPurchaseContacts(String creditCode, String id) {
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_CONTACT_WITH_INVESTMENT);
        dto.setPage(1);
        dto.setPage_size(100);

        if (!creditCode.equals("")) {
            dto.addFilterDtos("organizing_code", BaseTjFilterDto.OPERATE_CONTAIN, creditCode, DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_NONE);
        }
        dto.addFilterDtos("purchase_demand_id", BaseTjFilterDto.OPERATE_EQUAL, id, DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_AND);
        dto.addFilterDtos("data_source_code", BaseTjFilterDto.OPERATE_CONTAIN, "website_bid,trading_center", DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_AND);

        // 排序
        ArrayList<GetDeveloperSortDto> sorts = new ArrayList<>();
        GetDeveloperSortDto sort = new GetDeveloperSortDto();
        sort.setSort_type(GetDeveloperSortDto.SORT_DESC);
        sort.setAttribute_name("created_at");
        sort.setTable_name(DeveloperService.TABLE_CONTACT_WITH_INVESTMENT);
        sorts.add(sort);
        dto.setSorts(sorts);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        List<Map<String, Object>> listMap = new ArrayList<>();
        if (res.getData() == null || res.getData().getList() == null) {
            return listMap;
        }

        res.getData().getList().forEach(m -> {
            Map<String, Object> contact = new HashMap<>();
            contact.put("id", m.getItem().get("id").toString());
            contact.put("name", MyStringUtil.ReplaceSpecifiedStr(0, 1, m.getItem().get("ower").toString(), "*", 2));
            contact.put("mobile", MyStringUtil.ReplaceSpecifiedStr(0, 3, m.getItem().get("ower_mobile").toString(), "*", 8));

            listMap.add(contact);
        });
        return listMap;
    }

    public Map<String, Object> getContactInfo(String id) {
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_CONTACT_WITH_INVESTMENT);
        dto.setPage(1);
        dto.setPage_size(1);

        dto.addFilterDtos("id", BaseTjFilterDto.OPERATE_EQUAL, id, DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_NONE);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        if (res.getData() == null || res.getData().getList() == null || res.getData().getTotal() == 0) {
            return new HashMap<>();
        }

        return res.getData().getList().get(0).getItem();
    }

    public Map<String, Object> getContactInfoByUid(String uid) {
        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();

        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_CONTACT_WITH_INVESTMENT);
        dto.setPage(1);
        dto.setPage_size(1);

        dto.addFilterDtos("uid", BaseTjFilterDto.OPERATE_EQUAL, uid, DeveloperService.TABLE_CONTACT_WITH_INVESTMENT, BaseTjFilterDto.ASSOCIATE_NONE);

        BaseTjListResponseDto res = getDeveloperDataService.getFilteredDeveloperDetailList(dto);

        if (res.getData() == null || res.getData().getList() == null || res.getData().getTotal() == 0) {
            return new HashMap<>();
        }

        return res.getData().getList().get(0).getItem();
    }


    public FieldsSetting loadFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("id");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_contact";
        fieldsSetting.getFields().add(new DataApiField("uuid", groupName, "RowID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "联系人ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("source", groupName, "采购需求ID", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("company", groupName, "所在公司", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizingCode", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "区域（省）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "区域（省）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "区域（市）", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "区域（市）Code", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("sourceTitle", groupName, "招标标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("isInStock", groupName, "是否已添加", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("name", groupName, "联系人名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("firstName", groupName, "联系人姓", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("mobile", groupName, "联系人电话", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("ower_mobile_type", groupName, "联系人电话类型", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("createdPeriod", groupName, "最近更新时间", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    public ListDataResult loadData(LoadDataParams options) {
        GetContactListRequestDto dto = new GetContactListRequestDto();
        dto.setPageNum(options.getPageIndex() + 1);
        dto.setPageSize(options.getPageSize());
        dto.addFilterByLoadDataApi(options.getOptions().getFilters());
        if (dto.getOrganizing_code() == null) {
            throw new BusinessLogicException("信用代码为空");
        }
        if (dto.getProvince_code() != null && dto.getProvince_code().equals("0")) {
            dto.setProvince_code("");//如果是0,表示全国，则设置为空
        }
        SqlApiResponseDto res = getDeveloperDataService.getContactList(dto);
        if (res.getData() == null || res.getData().getRows().size() == 0) {
            ListDataResult result = new ListDataResult();
            result.setTotal(0);
            result.setData(new ArrayList<>());
            return result;
        }

        ListResult<DeveloperContactDto> listDataResult = new ListResult<>();
        List<DeveloperContactDto> developerContactDtos = new LinkedList<>();
        listDataResult.setTotal(res.getData().getTotalNum());

        // 获取是否添加过线索
        List<String> purchasesId = res.getData().getRows().stream().map(p -> p.get("purchase_demand_id").toString()).collect(Collectors.toList());
        Set<String> haveAdded = remoteClueService.isAdded(purchasesId);

        // 是否查看过
        Set<String> mobileSet = new HashSet<>();
        res.getData().getRows().forEach(d -> {
            mobileSet.add(d.get("ower_mobile").toString());
        });
        Map<String, OpTelViewHistory> opTelViewHistoryMap = provinceRadarService.getTelViewHistories(mobileSet);

        res.getData().getRows().forEach(d -> {
            DeveloperContactDto developerContactDto = new DeveloperContactDto();
            developerContactDto.setId(d.get("id").toString());
            // developerContactDto.setName(MyStringUtil.ReplaceSpecifiedStr(0, 1, d.get("ower").toString(), "*", 2));
            if (d.get("ower").toString().length() >= 1) {
                developerContactDto.setFirstName(d.get("ower").toString().substring(0, 1));
            }
            // developerContactDto.setMobile(MyStringUtil.ReplaceSpecifiedStr(0, 3, d.get("ower_mobile").toString(), "*", 8));
            developerContactDto.setName(d.get("ower").toString());
            developerContactDto.setMobile(d.get("ower_mobile").toString());
            developerContactDto.setCreatedPeriod(timeService.getLatestPeriod(d.get("created_at")) + "更新");
            if (d.get("created_at") != null) developerContactDto.setUpdatedTime(d.get("created_at").toString());
            developerContactDto.setSource(d.get("purchase_demand_id").toString());
            developerContactDto.setSourceTitle(d.get("title").toString());
            developerContactDto.setCompany(d.get("sub_developer_name").toString());
            developerContactDto.setOrganizingCode(d.get("sub_organizing_code").toString());
            // 是否添加过
            int hasAdded = haveAdded.contains(d.get("purchase_demand_id").toString()) ? 1 : 0;
            developerContactDto.setIsInStock(hasAdded);

            if (opTelViewHistoryMap.containsKey(d.get("ower_mobile").toString())) {
                developerContactDto.setViewTimes(opTelViewHistoryMap.get(d.get("ower_mobile").toString()).getViewTimes());
            }
            developerContactDtos.add(developerContactDto);
        });

        listDataResult.setData(developerContactDtos);
        //处理返回数据结构
        ListDataResult result = new ListDataResult();
        result.setTotal(listDataResult.getTotal());
        result.setData(listDataResult.getData());
        return result;
    }
}
